<?php
/**
 *@copyright
 */

/**
 *This class is the pupeteer of the Kat-Manager
 *All requests for web-pages comes through here and this decides which models will be used.
 *
 *Being a Controller the goal of this class is to route and control how and where the data will
 *be manipulated.  All data manipulation will be done by the models, which will contain the business
 *logic.  After the data has been manipulated the controller than passes its data to the view where
 *it is then displayed and formatted.
 */
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Kat extends CI_Controller {

    /**
     *Call CodeIgniter constructer to verify this classes status as a controller
     *Also starts the SESSION
     */
    function __construct() {
        parent::__construct();
        session_start();
        $this->load->library('session');
    }
    
    /**
     *This function determines whether or nota valid user is logged in
     *if user is not valid it routes the user to the login page
     */
    public function index() {
        $this->load->model('user');
        if (isset($_SESSION['user']) && $this->user->doesUserExist($_SESSION['user'])) {
            $this->route();
            return;
        }
        $this->login();
        return;
    }

    /**
     *This function handles the route selections page and all user interactions.
     *In addition this function ensures the current user has proper permissions
     *to view the page.
     */
    public function route() {
        unset($_SESSION['mode']);
        $errMsg = '';
        $successMsg = $this->session->flashdata('success_message');
        $this->load->model('user');
        $this->verifyUser();

        /*
         *The following secction determains where to route the user depending on
         *the button they press
         */
        
        //Drop/delete route button is pressed
        if (isset($_POST['Delete_Route']) && $_POST['Delete_Route'] == 'Delete Route') {
            $routeData = explode('|', $_POST['routeSelect']);
            $this->droproute($routeData[0]);
            $routes = $this->routes->getAllRoutes();
            return;
        }

        //if logout button is pressed
        if (isset($_POST['Logout']) && $_POST['Logout'] == 'Logout') {
            $this->logout();
            // $this->login();
            return;
        }

        // if user management button is pressed
        if (isset($_POST['User_Management']) && $_POST['User_Management'] == 'User Management') {
            $this->usermanager();
            return;
        }

        // if add route button is pressed
        if (isset($_POST['Add_Route']) && $_POST['Add_Route'] == 'Add Route') {
            $this->addroute();
            return;
        }

        //if help_management is built
        if (isset($_POST['Help_Management']) && $_POST['Help_Management'] == 'Help Management') {
            $this->help();
            return;
        }

        //if route button is pressed
        if (isset($_POST['Select_Route']) && $_POST['Select_Route'] == 'Select Route') {
            //   $_SESSION['routeSelect'] = $_POST['routeSelect'];
            $routeData = explode('|', $_POST['routeSelect']);
            $this->editroute($routeData[0], $routeData[1]);
            //    redirect('/kat/editroute');
            return;
        }

        $this->load->model('routes');   //load our routes object
        $routes = $this->routes->getAllRoutes();

        $data = array(
            'errMsg' => $errMsg,
            'successMsg' => $successMsg,
            'routes' => $routes,
        );
        
        //load our views
        $this->load->view('head');
        $this->load->view('route', $data);
    }

    /**
     *This function controls the user interaction on the editroute page
     */
    public function editroute($routeNumber, $direction = null) {
        $errMsg = '';
        $success = $this->session->flashdata('success_message');
        $this->load->model('user');

        $this->verifyUser();
        $this->load->model('routes');
    
        
        //if the user has submitted data, decipher what was clicked and route appropriately
        if (isset($_POST['submit'])) {
            if($_POST['ampm'] == 'pm'){
                $hour = $_POST['hour'];
                if($_POST['hour'] < 12){
                    $hour += 12;
                    
                }
                if($_POST['minute'] < 10){
                    $_POST['minute'] = '0' . $_POST['minute'];
                }
                $time = $hour . $_POST['minute'];
            }
            else{
                if($_POST['hour'] == 12){
                    $_POST['hour'] = '00';
                }
                if($_POST['minute'] < 10){
                    $_POST['minute'] = '0' . $_POST['minute'];
                }
                $time = $_POST['hour'] . $_POST['minute'];
            }
            if ($_POST['submit'] == 'Edit Stop') {
		$_SESSION['mode'] = 'edit';
                $this->routes->editRoute($_POST['id'], $_POST['location'], $_POST['day'], $time, $_POST['direction']);
                $success = "Route Number: {$_POST['id']} Has Been Edited";
            }
            if ($_POST['submit'] == 'Add Stop') {
			if($this->routes->checkIfRecordExists($routeNumber, $_POST['location'], $time)){
				$errMsg = "Sorry, There is a duplicate entry";
			}
			else{
                $this->routes->addRoute($routeNumber, $_POST['location'], $_POST['day'], $time, $_POST['direction']);
                $success = "Route Has Been Created";
				}
            }
			 if ($_POST['submit'] == 'Delete Stop') {
			 
				$this->routes->deleteRouteRecord($_POST['id']);
                $success = 'Stop has been deleted';
            }
        }//end if isset(POST)
        
        $routeArray = $this->routes->getRouteData($routeNumber, $direction);
        $data = array(
            'errMsg' => $errMsg,
            'successMsg' => $success,
            'routeArray' => $routeArray,
            'direction' => $direction,
            'routeNumber' => $routeNumber
        );
        $this->load->view('head');
        $this->load->view('editroute', $data);
    }

    /**
     *This function controls the user interaction with the
     *drop/delete route page.
     */
    public function droproute($routeNumber) {
        $errMsg = '';
        $successMsg = '';
        $this->load->model('user');
        $this->load->model('realms');
        $this->load->model('routes');   //load our routes object
        
        //check user
        $this->verifyUser("ADMIN");

        //if the user clicked drop route, before that logic!
        if (isset($_POST['Delete_Route'])) {
            if ($_POST['Delete_Route'] == 'Delete Route') {
                $this->routes->deleteRoute($routeNumber);
                $successMsg = "Route Number: {$routeNumber} Has Been Deleted";
            }
        }

        $routes = $this->routes->getAllRoutes();

        $data = array(
            'errMsg' => $errMsg,
            'successMsg' => $successMsg,
            'routes' => $routes,
        );
        $this->load->view('head');
        $this->load->view('route', $data);
    }

    /**
     *This function controls the user interactions with the login page
     */
    public function login() {
        $errMsg = '';
        $this->load->model('user');

        if (isset($_POST['login']) && $_POST['login'] == 'Login') {
            $errMsg = $this->user->loginUser($_POST['username'], $_POST['password']);
            if ($errMsg == '') {
                $this->route();
                return;
            }
        }//end if(isset(POST))
        $data = array(
            'errMsg' => $errMsg
        );
        $this->load->view('head');
        $this->load->view('login', $data);
    }

    /**
     *This function handles the logic involved with successfully logging a user out
     *If the button is pressed the user is logged out using the mode
     */
    public function logout() {
        $errMsg = '';
        $successMsg = '';

        $this->load->model('user');

        if (isset($_SESSION['user']) && $_SESSION['user'] != '') {
            $this->user->logout();
            $successMsg = 'Successfully Logged Out';
        } else {
            if (isset($_SESSION)) {
                $errMsg = '';
                $successMsg = '';
            } else {
                $errMsg = 'Could not logout';
            }
        }
        $data = array(
            'errMsg' => $errMsg,
            'successMsg' => $successMsg,
        );
        $this->load->view('head');
        $this->load->view('login', $data);
    }

    /**
     *This function controls the logic of the usermanager page.
     */
    public function usermanager() {
        $errMsg = '';
        $successMsg = '';
        $this->load->model('user');
        $this->load->model('realms');
        $this->verifyUser("ADMIN");
        
         //if the user hit submit, route the data manipulation appropriately.
        if (isset($_POST['submit'])) {

            if ($_POST['submit'] == 'Update User') {
                $errMsg = $this->user->editUser($_POST['id'], $_POST['username'], $_POST['realmSelect']);
                if (strlen($errMsg) == 0)
                    $successMsg = "{$_POST['username']} is now of realm: {$_POST['realmSelect']}";
            }
            if ($_POST['submit'] == 'Change Password') {
                $errMsg = $this->user->passwordValidate($_POST['password'], $_POST['confirmPassword']);
                if (strlen($errMsg) == 0) {
                    $this->user->changePassword($_POST['id'], $_POST['username'], $_POST['password']);
                    $successMsg = "Password Changed For: {$_POST['username']}.";
                }
            }
            if ($_POST['submit'] == 'Add User') {
                $errMsg = $this->user->passwordValidate($_POST['password'],$_POST['confirmPassword']);
                $errMsg .= $this->user->validateUsername($_POST['username']);
                if($this->user->doesUserExist($_POST['username']))
                    $errMsg .= "Username already exists. ";
                if (strlen($errMsg) == 0) {
                    $this->user->createUser($_POST['username'], $_POST['password'], $_POST['realmSelect']);
                    $successMsg = "User, {$_POST['username']}, has been created.";
                }
            }

            if ($_POST['submit'] == 'Delete User') {
                //$errMsg = $this->user->passwordValidate($_POST['password'],$_POST['confirmPassword']);
                if (strlen($errMsg) == 0) {
                    $this->user->deleteUser($_POST['username']);
                    $successMsg = "User, {$_POST['username']}, has been deleted.";
                }
            }
        }// end if(isset(POST[submit]))

        $userList = $this->user->getUserList();
        $realmList = $this->realms->getAllRealms($_SESSION['realm']);
        $data = array(
            'errMsg' => $errMsg,
            'userList' => $userList,
            'realmList' => $realmList,
            'successMsg' => $successMsg
        );
        $this->load->view('head');
        $this->load->view('usermanager', $data);
    }
    
    /**
     *This function controlls the logic involved for a
     *request of the database table dump.  Upon success
     *the file is created and the user is redirected to the
     *said file.
     */
    public function gettable($dataType){
        
        $this->load->model('routes');
        $this->load->helper('url'); //needed for redirect
        
        $is_file_created = $this->routes->create_file($dataType);
        if($is_file_created){
            //redirect("./resources/data/routetable.$dataType");
            $this->session->set_flashdata('success_message', 'Updates successfully committed.');
            redirect('/index.php/kat/route', 'location', 301);
        }
        else
            echo "Error!";
    }

    /**
     *This function is responsible for controlling the logic of the
     *addroute page.
     */
    public function addroute() {
        $errMsg = '';
        $success = '';
        $routeArray = '';
        $this->load->model('user');
        $this->load->model('routes');
        $this->load->helper('url');

        $this->verifyUser();

        if (isset($_POST['submit'])) {
            if($_POST['ampm'] == 'pm'){
                $hour = $_POST['hour'];
                if($_POST['hour'] < 12){
                    $hour += 12;
                    
                }
                if($_POST['minute'] < 10){
                    $_POST['minute'] = '0' . $_POST['minute'];
                }
                $time = $hour . $_POST['minute'];
            }
            else{
                if($_POST['hour'] == 12){
                    $_POST['hour'] = '00';
                }
                if($_POST['minute'] < 10){
                    $_POST['minute'] = '0' . $_POST['minute'];
                }
                $time = $_POST['hour'] . $_POST['minute'];
            }

            if ($_POST['submit'] == 'Edit Stop') {
                $this->routes->editRoute($_POST['id'], $_POST['location'], $_POST['day'], $time, $_POST['direction']);
                $success = "Entry Number: {$_POST['id']} Has Been Edited";
            }

            if ($_POST['submit'] == 'Add Route') {
                if ($this->routes->checkIfRouteExists($_POST['routenumber']) == false) {//Check if route exists
                    //Check for duplicate entries
                    if ($_POST['submit'] != 'Send Changes' && $this->routes->checkIfRecordExists($_POST['routenumber'], $_POST['location'], $time)) {
                        $errMsg = "Sorry, there was a duplicate entry, please edit the record in table.";
                    } else {//No duplicate entries, insert
                        $_SESSION['mode'] = 'edit';
                        $this->routes->addRoute($_POST['routenumber'], $_POST['location'], $_POST['day'], $time, $_POST['direction']);
                        $this->session->set_flashdata('success_message', "Route $_POST[routenumber] Has Been Created");
                        redirect("/index.php/kat/editroute/{$_POST['routenumber']}", 'location', 301);
                    }
                } else {
                    if (isset($_SESSION['mode'])) {
                        $errMsg = "You are editing Route $_POST[routenumber], continue adding stops ";
                    } else {
                        $errMsg = "Sorry, Route $_POST[routenumber] already exists";
                    }
                }
            }

            if ($_POST['submit'] == 'Add Stop') {
                if ($_POST['submit'] != 'Send Changes' && $this->routes->checkIfRecordExists($_POST['routenumber'], $_POST['location'], $time)) {
                    $errMsg = "Sorry, there was a duplicate entry, please edit the record in table.";
                } else {
                    $this->routes->addRoute($_POST['routenumber'], $_POST['location'], $_POST['day'], $time, $_POST['direction']);
                    $success = "Another entry for Route $_POST[routenumber] Has Been added";
                    //$_SESSION['id'] ++; // this insert at the end of the database, whenever I did an insert it was at record 0.
                }
            }

            if ($_POST['submit'] == 'Delete Stop') {
                $this->routes->deleteRouteRecord($_POST['id']);
                $success = 'Stop has been deleted';
            }
        }//end if(POST(submit))

        if (isset($_POST['routenumber']))
            $routeArray = $this->routes->getRouteData($_POST['routenumber']);
        $data = array(
            'errMsg' => $errMsg,
            'successMsg' => $success,
            'routeArray' => $routeArray
        );
        $this->load->view('head');
        $this->load->view('addroute', $data);
    }

//this function will be called by all the page actions.
//this function will determain if the user is allowed to view that page or not
//@TODO - Add additional ability to scale realm verification  
    public function verifyUser($minimumRealm = NULL) {
        $this->load->model('user');
        $this->load->model('realms');
        $this->load->helper('url');
        //check user
        if (!isset($_SESSION['user']) || !$this->user->doesUserExist($_SESSION['user'])) {

            redirect('/index.php/kat/login', 'location', 301);
        }
        //verify Realm
        //call to realms model where a function will take care of scaling of realms
        if (isset($minimumRealm)) {
            if (!isset($_SESSION['realm']) || strtoupper($_SESSION['user']) != strtoupper($minimumRealm)) {
                redirect('/index.php/kat/route', 'location', 301);
            }
        }
    }

    /**
     *This function controls the logic involved with the help page.
     *
     *@todo Implement logic so KatApp can pull the help screens
     */
    public function help() {
        $errMsg = '';
        $successMsg = '';

        $this->load->model('helpscreen');
        $this->verifyUser("ADMIN");

        if (isset($_POST['informationText'])) {
            if (strlen($_POST['informationText']) > 0) {
                $this->helpscreen->setInformation($_POST['informationText']);
                $successMsg = "Information Screen Updated!";
            } else
                $errMsg = "Text field must be longer than 0 characters";
        }
        if (isset($_POST['scanningText'])) {
            if (strlen($_POST['scanningText']) > 0) {
                $this->helpscreen->setScanning($_POST['scanningText']);
                $successMsg = "Scanning Screen Updated!";
            } else
                $errMsg = "Text field must be longer than 0 characters";
        }
        if (isset($_POST['routingText'])) {
            if (strlen($_POST['routingText']) > 0) {
                $this->helpscreen->setRouting($_POST['routingText']);
                $successMsg = "Routing Screen Updated!";
            } else
                $errMsg = "Text field must be longer than 0 characters";
        }
        $information = $this->helpscreen->getInformation();
        $scanning = $this->helpscreen->getScanning();
        $routing = $this->helpscreen->getRouting();
        $data = array(
            'errMsg' => $errMsg,
            'successMsg' => $successMsg,
            'information' => $information,
            'scanning' => $scanning,
            'routing' => $routing
        );
        $this->load->view('head');
        $this->load->view('help', $data);
    }

}
